#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h> 
#include <arpa/inet.h>
#include <mysql.h>
#include <pthread.h>

struct password
{
	char id[20];
	char passwd[20];
	int flag;
};

int sockfd;

#define SIZE 5
#define MAX 100

int main()
{	
	struct sockaddr_in localaddr;
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(sockfd == -1)
	{
		perror("socket");
	}
	memset(&localaddr,0x00,sizeof(localaddr));
   	localaddr.sin_family = AF_INET;
    	localaddr.sin_port = htons(6666);
	localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	if(0 != bind(sockfd,(struct sockaddr *)&localaddr,sizeof(struct sockaddr_in)))
	{
		perror("bind");
		exit(0);	
	}
	printf("等待用户连接.......");	
	if (0 != listen(sockfd,SIZE))
	{
       		perror("listen");
        	exit(0);
    	}

	fd_set allset,rset;
	int maxfd = sockfd;
	int clientfd[FD_SETSIZE];
	FD_ZERO(&allset);
	FD_SET(sockfd,&allset);
	FD_SET(STDIN_FILENO,&allset);
	memset(clientfd,-1,sizeof(clientfd));
	int fd,len,nread,flag;
	struct sockaddr_in remoteaddr;
	while(1)
	{
		rset = allset;
		nread = select(maxfd+1,&rset,NULL,NULL,NULL);
		if(nread < 0)
		{
			perror("select");
		}

		if(FD_ISSET(sockfd,&rset))
		{
			fd = accept(sockfd,(struct sockaddr *)&remoteaddr,&len);
			if(fd<0)
			{
				perror("accept");
			}
			int i;
			for(i=0;i<FD_SETSIZE;i++)
			{
				if(clientfd[i]==-1)
				{
					clientfd[i]=fd;
					break;
				}
			}
			if(fd>maxfd)
			{
				maxfd=fd;	
			}
			FD_SET(fd,&allset);
			if(nread<=1)
			{
				continue;
			}
		}

		int i;
		for(i=0;i<maxfd;i++)
		{
			if(clientfd[i]!=-1&&FD_ISSET(clientfd[i],&rset))
			{
				struct password pw;
				memset(&pw,'\0',sizeof(pw));
				if(recv(clientfd[i],&pw,sizeof(pw),0)<=0)
				{
					perror("recv");
					close(clientfd[i]);
					FD_CLR(clientfd[i],&allset);
					exit(clientfd[i]);
					clientfd[i]=-1;
					continue;
				}
				body(clientfd[i],pw);
				//char buf[10];
				//recv(clientfd[i],buf,sizeof(buf),0);
				//if(strcmp(buf,"quit\n")==0)
				//{
				//	exit(clientfd[i]);
				//}
				
			}	
		}
	}		
    	close(sockfd);
    	return 0;
}

